/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useRef, useState, useMemo } from 'react';
import ProTable from '@ant-design/pro-table';
import DragTable from '@/components/DragTable';
import { Radio, notification, Space } from 'antd';
import { getPddComplainList } from '@/services/customerServiceTools';
import { connect, useSelector } from 'umi';
import type { ConnectState } from '@/models/connect';
import type { RadioChangeEvent } from 'antd';
import type { Dispatch } from 'umi';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { PddUnTableListItem, RecordDetail } from '../types/PDDComplaintOrder';
import HandlingDrawerForm from './HandlingDrawerForm';

interface TimeButton {
  name: string;
  key: number;
}

export type ComplaintOrderPropsType = 'todo' | 'secondComplaint' | 'finished';

interface ComplaintOrderProps {
  type: ComplaintOrderPropsType;
  activeKey: ComplaintOrderPropsType;
  dispatch: Dispatch;
}

const timeButtonArr: TimeButton[] = [
  {
    name: '全部',
    key: 0,
  },
  {
    name: '待审核',
    key: 10,
  },
  {
    name: '滞留16小时',
    key: 1,
  },
  {
    name: '滞留12小时 未处理',
    key: 2,
  },
  {
    name: '滞留12小时 处理中',
    key: 3,
  },
  {
    name: '滞留8小时 未处理',
    key: 4,
  },
  {
    name: '滞留8小时 处理中',
    key: 5,
  },
  {
    name: '滞留4小时 未处理',
    key: 6,
  },
  {
    name: '滞留4小时 处理中',
    key: 7,
  },
];

const ComplaintOrder: React.FC<ComplaintOrderProps> = ({ type, dispatch, activeKey }) => {
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const actionRef = useRef<ActionType>();
  const [searchValue, setSearchValue] = useState<string>('');
  const [time, setTime] = useState<number | string>(0);
  const [visible, setVisible] = useState<boolean>(false);
  const [record, setRecord] = useState<PddUnTableListItem>({});

  const handleDetail = (open: boolean, data: PddUnTableListItem) => {
    setVisible(open);
    setRecord(data);
  };

  const reloadTable = () => actionRef.current?.reload();

  const passRecordToPDD = (record_id: any) => {
    dispatch({
      type: 'pddComplaint/passRecordToPDD',
      payload: {
        record_id,
      },
    }).then(() => {
      reloadTable();
      notification.success({
        message: '提交成功，已提交给拼多多。',
      });
    });
  };

  const columns: ProColumns<PddUnTableListItem>[] = [
    {
      title: '运单号',
      dataIndex: 'waybill_no',
      width: '200px',
      align: 'center',
      search: false,
    },
    {
      title: type === 'todo' || type === 'finished' ? '投诉原因' : '二次投诉原因',
      dataIndex: 'complaint_type_text',
      align: 'center',
      search: false,
      width: '300px',
    },
    {
      title: '处理结果',
      // dataIndex: 'inn_name',
      align: 'center',
      search: false,
      width: '300px',
      render: (_, data: any = {}) => {
        const { is_deal, records }: { is_deal: string; records: RecordDetail } = data;
        const { act_info: { act_desc, act_info, act_money } = {} } = records;
        const needPay = act_info === '包裹丢失';

        const result = `${act_info} ${
          needPay ? (act_money == '0' ? '无需赔偿' : `，已赔付${Number(act_money) / 100}元`) : ''
        }${act_desc ? `-${act_desc}` : ''}`;

        if (is_deal === '1' || is_deal === '3') {
          return result;
        }
        return '';
      },
    },
    {
      title: '驿站手机号',
      dataIndex: 'inn_phone',
      align: 'center',
      search: false,
      width: '300px',
    },
    {
      title: '投诉时间',
      dataIndex: 'create_at',
      width: '300px',
      align: 'center',
      search: false,
    },
    {
      title: '滞留时间',
      dataIndex: 'last_hour',
      width: '100px',
      align: 'center',
      search: false,
      hideInTable: type === 'finished',
      render: (text: any) => {
        if (text >= 16) {
          return <span style={{ color: 'red' }}>{text}小时</span>;
        }
        return `${text}小时`;
      },
    },
    {
      title: '完结时间',
      dataIndex: 'operate_at',
      width: '300px',
      align: 'center',
      search: false,
      hideInTable: type !== 'finished',
    },
    {
      title: '处理人',
      dataIndex: 'act_name',
      width: '200px',
      align: 'center',
      search: false,
      hideInTable: type !== 'finished',
      render: (_, data: any) => {
        const { records = {} } = data;
        const { act_info = {} } = records;
        const { act_source, act_tel, act_name } = act_info;
        const tel = act_tel?.slice(7, 11);
        return act_source === '驿站' ? `${act_source}-${act_name}` : `${act_source}-${tel}`;
      },
    },
    {
      title: '处理状态',
      dataIndex: 'is_deal',
      width: '100px',
      align: 'center',
      search: false,
      hideInTable: type === 'finished',
      render: (text) => {
        switch (text) {
          case '0':
            return '未处理';
          case '1':
            return '已处理';
          case '2':
            return '处理中';
          case '3':
            return '待审核';
          default:
            return '-';
        }
      },
    },
    {
      title: '操作',
      valueType: 'option',
      dataIndex: 'option',
      width: winSize === 'xs' ? 80 : 130,
      align: 'center',
      fixed: 'right',
      render: (_, data: any = {}) => {
        const { is_deal, records }: { is_deal: string; records: RecordDetail } = data;
        const { id } = records;
        const show = is_deal === '3' && type !== 'finished';
        return (
          <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
            {show && <a onClick={() => passRecordToPDD(id)}>审核通过</a>}
            <a onClick={() => handleDetail(true, data)}>{type === 'finished' ? '详情' : '处理'}</a>
          </Space>
        );
      },
    },
  ];

  const status: number = useMemo(() => {
    switch (type) {
      case 'todo':
        return 1;
      case 'secondComplaint':
        return 2;
      case 'finished':
        return 3;
      default:
        return 1;
    }
  }, [type]);

  const handleRequest = (params: any) => {
    const { current: page, pageSize, ...rest } = params;
    return getPddComplainList(
      {
        ...rest,
        page,
        pageSize,
      },
      (list: any) => {
        const ids = list.map((val: any) => val.id);
        dispatch({
          type: 'pddComplaint/save',
          payload: {
            [`${activeKey}_page_ids`]: ids,
          },
        });
      },
    );
  };

  const onTimeClick = (e: RadioChangeEvent) => {
    const key = e.target.value;
    setTime(key);
    // 重置分页
    const { reloadAndRest } = actionRef.current || {};
    if (reloadAndRest) {
      reloadAndRest();
    }
  };

  return (
    <>
      <div style={{ background: '#fff', padding: '24px 0 0 8px' }}>
        <Radio.Group value={time} onChange={onTimeClick}>
          {timeButtonArr.map((val) => (
            <Radio.Button value={val.key} key={val.key}>
              {val.name}
            </Radio.Button>
          ))}
        </Radio.Group>
      </div>
      <DragTable>
        <ProTable<PddUnTableListItem>
          className='kb-pro-table'
          actionRef={actionRef}
          rowKey='id'
          request={handleRequest}
          columns={columns}
          pagination={{
            pageSize: 50,
            showQuickJumper: false,
            showSizeChanger: false,
          }}
          params={{
            search: searchValue,
            ret_type: time,
            status,
          }}
          toolbar={{
            search: {
              placeholder: '运单号/工单号/驿站手机号',
              allowClear: true,
              enterButton: '搜索',
              style: { width: 300 },
              onSearch: (value: string) => {
                const { reloadAndRest } = actionRef.current || {};
                if (!value && reloadAndRest) {
                  reloadAndRest();
                }
                setSearchValue(value);
              },
            },
            settings: [],
          }}
          search={false}
          scroll={{ x: 640 }}
        />
      </DragTable>

      <HandlingDrawerForm
        reloadTable={reloadTable as any}
        visible={visible}
        triggleVisible={setVisible}
        id={record.id}
        type={type}
        activeKey={activeKey}
      />
    </>
  );
};

export default connect()(React.memo(ComplaintOrder));
